import axios from 'axios';
// import router from '../routerManuaConfig'
import router from '../router/index'
import store from "../store";
import Vue from 'vue';
import qs from "qs";
import applicationUserManager from "../Auth/applicationusermanager";



// 请求延时
axios.defaults.timeout = 20000
// axios.defaults.headers = {
//     "content-type":"application/json;charset=UTF-8"
//    }
//axios.defaults.headers.get['Content-Type'] = 'application/json;charset=UTF-8';
//axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
var storeTemp = store;
axios.interceptors.request.use(
    config => {
        var curTime = new Date()
        var expiretime = new Date(Date.parse(storeTemp.state.tokenExpire))

        if (storeTemp.state.token && (curTime < expiretime && storeTemp.state.tokenExpire)) {
            // 判断是否存在token，如果存在的话，则每个http header都加上token
            config.headers.Authorization = "Bearer " + storeTemp.state.token;
        }

        saveRefreshtime();

        return config;
    },
    err => {
        return Promise.reject(err);
    }
);

// http response 拦截器
axios.interceptors.response.use(
    response => { 
        return response; 
    },
    error => {
        let errInfo = { IsSuccess: false, Message: "错误" }
        // 超时请求处理
        var originalRequest = error.config;
        if(error.code == 'ECONNABORTED' && error.message.indexOf('timeout')!=-1 && !originalRequest._retry){
            errInfo.Message = "请求超时！"; 
            originalRequest._retry = true 
        }else if (error.response) {
            if (error.response.status == 401) {
                var curTime = new Date()
                var refreshtime = new Date(Date.parse(window.localStorage.refreshtime))
                // 在用户操作的活跃期内
                if (window.localStorage.refreshtime && (curTime <= refreshtime)) {
                    return  refreshToken({token: window.localStorage.Token}).then((res) => {
                        if (res.success) {
                            Vue.prototype.$message({
                                message: 'refreshToken success! loading data...',
                                type: 'success'
                            });

                            store.commit("saveToken", res.response.token);

                            var curTime = new Date();
                            var expiredate = new Date(curTime.setSeconds(curTime.getSeconds() + res.response.expires_in));
                            store.commit("saveTokenExpire", expiredate);

                            error.config.__isRetryRequest = true;
                            error.config.headers.Authorization = 'Bearer ' + res.response.token;
                            return axios(error.config);
                        } else {
                            // 刷新token失败 清除token信息并跳转到登录页面
                            ToLogin()
                        }
                    });
                } else {
                    // 返回 401，并且不知用户操作活跃期内 清除token信息并跳转到登录页面
                    ToLogin()
                }

            }
            // 403 无权限
            else if (error.response.status == 403) {
               errInfo.Message = "失败！该操作无权限"; 
            }
            // 429 ip限流
            else if (error.response.status == 429) {
                errInfo.Message = "刷新次数过多，请稍事休息重试！";
            }else if (error.response.status == 404) {
                // 404 不存在
                errInfo.Message = "失败！访问接口不存在";
           }else if (error.response.status == 500) {
               // 500 服务器异常
               errInfo.Message = "失败！服务器异常"; 
           }else if (error.response.status == 405) {
               // 405 请求http方法错误
               errInfo.Message = "失败！请求http方法错误";  
           }else if (error.response.status == 415) {
               // 415 参数没有指定Body还是Query
               errInfo.Message = "失败！参数没有指定Body还是Query";   
           }else {
               //其他错误参数
                errInfo.Message = '失败！请求错误' + error.response.status;    
           }
        }else{
            errInfo.Message = "失败！服务器断开";  
        }
        Vue.prototype.$message({
            message: errInfo.Message,
            type: 'error'
        });
        return errInfo; // 返回接口返回的错误信息
    }
);


export const saveRefreshtime = params => {

    let nowtime = new Date();
    let lastRefreshtime = window.localStorage.refreshtime ? new Date(window.localStorage.refreshtime) : new Date(-1);
    let expiretime = new Date(Date.parse(window.localStorage.TokenExpire))

    let refreshCount=1;//滑动系数
    if (lastRefreshtime >= nowtime) {
        lastRefreshtime=nowtime>expiretime ? nowtime:expiretime;
        lastRefreshtime.setMinutes(lastRefreshtime.getMinutes() + refreshCount);
        window.localStorage.refreshtime = lastRefreshtime;
    }else {
        window.localStorage.refreshtime = new Date(-1);
    }
};
 const ToLogin = params => {
     
     store.commit("saveToken", "");
     store.commit("saveTokenExpire", "");
     store.commit("saveTagsData", "");
     window.localStorage.removeItem('user');
     window.localStorage.removeItem('NavigationBar');

     
                
    if (global.IS_IDS4) {
        applicationUserManager.login();
    } else {
        router.replace({
            path: "/login",
            query: {redirect: router.currentRoute.fullPath}
        }); 
        //window.location.reload()
    }
};

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function get(url, params) {
    return axios.get(url, { params: params }).then(res => res.data);
}


/** 
 * post方法，对应post请求 
 * @param {String} url [请求的url地址] 
 * @param {Object} params [请求时携带的参数] 
 */
export function post(url, params) {
    return axios.post(url, params)
}


/** 
 * post方法，对应post请求 
 * @param {String} url [请求的url地址] 
 * @param {Object} params [qs.stringify请求时携带的参数] 
 */
export function postStringify(url, params) {
    console.log(params);
    return axios.post(url, qs.stringify(params))
}

export function _delete(url, params) {
    return axios.delete(url, {params:params})
}